package com.marcosnobrega.android.threadservice;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.marcosnobrega.android.activity.AndroidNetwork;

import android.os.Handler;

public final class UpdatePresenceListThread implements Runnable{
	
	private String myAndroidId;
	private Runnable mRunnable;
	private Handler mHandler;
	private int lastCount;
	static final UpdatePresenceListThread updatePresenceThread = new UpdatePresenceListThread();
	
	public static final UpdatePresenceListThread getInstance(Runnable runnable, Handler handler, String userAndroidId){
		updatePresenceThread.lastCount = 0;
		updatePresenceThread.mHandler = handler;
		updatePresenceThread.mRunnable = runnable;
		updatePresenceThread.myAndroidId = userAndroidId;
		return updatePresenceThread;
	}
	
	private UpdatePresenceListThread(){}

	@Override
	public void run() {
		while(true){
			try {
				//loadUsersList();
				this.mHandler.post(this.mRunnable);
				Thread.sleep(3000);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	private void loadUsersList() throws Exception{
		
		HttpPost request = new HttpPost(AndroidNetwork.getServiceUrl()+"?action="+AndroidNetwork.getActionListUsers());
		
		DefaultHttpClient client = new DefaultHttpClient();
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("userAndroidId", myAndroidId));
		
		request.setEntity(new UrlEncodedFormEntity(params));
		
		HttpResponse response = client.execute(request);
		HttpEntity entity = response.getEntity();
		String responseText = EntityUtils.toString(entity);
		if(!responseText.equalsIgnoreCase("")){
			String[] users = responseText.split(";;;");
			if(this.lastCount != users.length){
				this.lastCount = users.length;
				this.mHandler.post(this.mRunnable);
			}
		}
		
	}

}
